<template>
    <el-tabs v-model="selected" type="border-card" closable @tab-change="tabChange" @tab-remove="tabRemove">
        <el-tab-pane v-for=" (item, index)  in items" :label="item!.name" :key="index" :name="item!.name">
        </el-tab-pane>
        <router-view></router-view>
    </el-tabs>
</template>

<script setup lang="ts">

import router from '@/router'

type TabItem = {
    path: string
    name: string
} | undefined

const items = reactive<TabItem[]>([]);

const selected = ref('')

const props = defineProps<{ path: string }>()


watch(props, (props) => {

    let tableItem = toTabItem(props.path) as TabItem;

    if (!items.map((value) => { return value!.path }).includes(props.path)) {
        items.push(tableItem);
    }

    selected.value = tableItem!.name
})


function toTabItem(path: string): TabItem | undefined {
    let rotues = router.getRoutes();
    for (let route of rotues) {
        if (route.path == path) {
            return { name: route.name as string, path }
        }
    }
}

function tabChange(tabName: any) {
    items.forEach(e => {
        if (e!.name === tabName) {
            selected.value = tabName
            router.push(e!.path)
        }
    })
}

function tabRemove(targetName: any) {
    let activeName = selected.value
    if (activeName === targetName) {
        items.forEach((tab, index) => {
            if (tab!.name === targetName) {
                const nextTab = items[index + 1] || items[index - 1]
                if (nextTab) {
                    activeName = nextTab.name
                }
            }
        })
    }
    selected.value = activeName
    let removeIndex = -1
    items.forEach((item, index) => {
        if (item!.name === targetName) {
            removeIndex = index
        }
    })
    items.splice(removeIndex, 1)
}
</script>

<style scoped>
.el-tabs {
    height: 99%;
    box-shadow: var(--el-box-shadow-light);
    border-radius: 4px;
}
</style>